package com.zhudi.develop_demo_as;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.zhudi.develop.util.ZhudiDebugLog;
import com.zhudi.develop.util.ZhudiSystemInfoUtil;
import com.zhudi.develop_demo_as.message.MessageParameter;
import com.zhudi.develop_demo_as.network.MyHttpClient;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangdan on 15-1-16.
 */
public abstract class TemplateFragment extends BaseFragment {
    private MyHttpClient client;
    private List<RequestHandle> requestHandles = new ArrayList<RequestHandle>();
    private static ProgressDialog pd = null;
    // URL
    protected abstract String prepareURL(MessageParameter mp) throws Exception;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        client = new MyHttpClient();
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    /**
     * 连接网络
     *
     * @param msgParameter
     * @param jsonParser
     *
     */
    protected void processThread(final MessageParameter msgParameter,final JsonObjectParser jsonParser) {
        // 判断网络是否连接
        if (!ZhudiSystemInfoUtil.checkNetWorkStatus(getActivity())) {
            //ZhudiToastSingle.showToast(this, R.string.data_load_fail, false);
            return;
        }
        if (msgParameter.showDialog) {
            showLoadingDialog(msgParameter, true);
        }
        final String url = madeURL(msgParameter);
        if (url == null)
            return;
        RequestHandle rh;
        if (msgParameter.stringParams == null) {
            rh = client.get(getActivity(), url, null, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    ZhudiDebugLog.d(new String(responseBody));
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                }

                @Override
                public void onFinish() {
                    dismissPd();
                }
            });
        } else {
            rh = client.post(getActivity(), url, msgParameter.stringParams, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                }

                @Override
                public void onFinish() {
                     dismissPd();
                }
            });
        }
        requestHandles.add(rh);
    }


    /**
     * 取消进度的显示
     */
    private void dismissPd() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
    }

    /**
     * 显示加载Dialog
     */
    private void showLoadingDialog(final MessageParameter msgParameter,boolean flag) {
        if (flag) {
            pd = ProgressDialog.show(getActivity(), null, "请稍等...");
            pd.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        dismissPd();
                        for (RequestHandle handle : requestHandles) {
                            if (!handle.isCancelled() && !handle.isFinished()) {
                                handle.cancel(true);
                            }
                        }
                    }
                    return false;
                }
            });
        }
    }

    private String madeURL(final MessageParameter msgParameter) {
        String tmpURL = null;
        try {
            tmpURL = prepareURL(msgParameter);
        } catch (Exception e) {
            ZhudiDebugLog.d(e.toString());
        }
        return tmpURL;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        client.cancelAllRequests(true);
    }
}
